<template>
    <div>
        <el-dialog :title="title" :visible.sync="dialogFormVisible" width="70%" @open='openDialog' @close='closeDialog'>
            <el-form :model="form" :rules="rules" ref="ruleForm">
                <el-form-item label="类目选择" :label-width="formLabelWidth" prop="category">
                    <el-button type="primary" @click="openCategory">类目选择</el-button>
                    <span style="margin-left:20px;">{{ form.category }}</span>
                </el-form-item>
                <el-dialog @close="closeCate" width="30%" title="类目选择" :visible.sync="innerVisible" append-to-body>
                    <el-tree :data="category_data" :props="defaultProps" @node-click="handleNodeClick"></el-tree>
                    <div slot="footer" class="dialog-footer">
                        <el-button @click="innerCancel">取 消</el-button>
                        <el-button type="primary" @click="innerConfirm">确 定</el-button>
                    </div>
                </el-dialog>
                <!-- <el-form-item label="商品参数" :label-width="formLabelWidth" v-if="form.category!=''" prop="param">
                    <el-table :data="GoodsParamData" border>
                        <el-table-column prop="params_name" label="参数名" width="120"></el-table-column>
                        <el-table-column prop="params" label="输入框" show-overflow-tooltip>
                            <template slot-scope="scope">
                                <el-input v-model="scope.row.params" @change="funtion" @input='getNum'
                                    placeholder="请输入内容" class="group-inp"></el-input>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-form-item> -->
                <el-form-item label="商品名称" :label-width="formLabelWidth" prop="name">
                    <el-input v-model="form.name" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="商品价格" :label-width="formLabelWidth" prop="price">
                    <el-input v-model="form.price" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="商品数量" :label-width="formLabelWidth" prop="num">
                    <el-input v-model="form.num" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="发布时间" :label-width="formLabelWidth">
                    <el-col :span="11">
                        <el-date-picker v-model="form.date" type="date" placeholder="选择日期" style="width: 100%;">
                        </el-date-picker>
                    </el-col>
                    <el-col :span="2" class="line">-</el-col>
                    <el-col :span="11">
                        <el-time-picker style="width: 100%;float:right" arrow-control v-model="form.time"
                            :picker-options="{
                                selectableRange: '18:30:00 - 20:30:00'
                            }" placeholder="选择时间">
                        </el-time-picker>
                    </el-col>

                </el-form-item>
                <el-form-item label="商品卖点" :label-width="formLabelWidth">
                    <el-input v-model="form.sellPoint" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="商品图片" :label-width="formLabelWidth">
                    <el-button type="primary" @click="openImgSub">上传图片</el-button>
                    <!-- 图片展示 -->
                    <div><img :src="form.image" style="width: 100px;height: auto; margin-top: 10px" alt=""
                            v-if="isSubmit" /></div>
                </el-form-item>
                <el-dialog width="30%" title="图片上传" :visible.sync="innerVisibleImg" append-to-body>
                    <el-upload class="upload-demo" ref="upload" action="/api/upload/" :on-preview="handlePreview"
                        :on-remove="handleRemove" :file-list="fileList" :auto-upload="false" :on-success="onSuccess"
                        :on-error='onError' :limit="1">
                        <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
                        <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器
                        </el-button>
                        <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb(仅上传一张)</div>
                    </el-upload>
                    <div slot="footer" class="dialog-footer">
                        <el-button @click="innerImgCancel">取 消</el-button>
                        <el-button type="primary" @click="innerImgConfirm">确 定</el-button>
                    </div>
                </el-dialog>
                <el-form-item label="商品描述" :label-width="formLabelWidth">
                    <WangEditor ref="change" />
                </el-form-item>

            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="CancelSub">取 消</el-button>
                <el-button type="primary" @click="submitForm">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import WangEditor from './WangEditor.vue';

export default {
    data() {
        return {
            //getParent:'',
            code: 0,//0表示直接添加是插入信息；1表示从编辑页面过来，是修改信息
            fileList: [],
            category_data: [],
            GoodsParamData:[],
            category_sel: "",
            category_temp: '',
            innerVisible: false,
            innerVisibleImg: false,
            dialogFormVisible: false,
            isSubmit: false,
            form: {
                id: '',
                category: "",
                name: "",
                price: "",
                num: "",
                date: "",
                time: "",
                image: "",
                sellPoint: "",
                delivery: false,
                type: [],
                resource: "",
                desc: ""
            },
            rules: {
                name: [
                    { required: true, message: "请输入商品名称", trigger: "blur" },
                    {
                        min: 2,
                        max: 10,
                        message: "长度在 2 到 10 个字符",
                        trigger: "blur",
                    },
                ],
                price: [{ required: true, message: "请输入商品价格", trigger: "blur" }],
                num: [{ required: true, message: "请输入商品数量", trigger: "blur" }],
            },
            defaultProps: {
                children: "children",
                label: "label"
            },
            formLabelWidth: "120px"
        };
    },
    methods: {
        openCategory() {
            this.innerVisible = true;
            this.$ajax({
                method: "get",
                url: "/api/getCategory",
            }).then(res => {
                this.category_data = JSON.parse(res.data.data)
            });
            
        },
        openImgSub() {
            this.innerVisibleImg = true;
        },
        getTreeNode(node) {
            if (node) {
                if (node.parent.label !== undefined) {
                    this.getTreeNode(node.parent);
                    this.category_sel += node.parent.label + '/'
                }
            }
        },
        handleNodeClick(data, node) {
            console.log('node:', node);
            console.log('data:', data);
            this.getTreeNode(node)
            this.category_sel += data.label;
            this.category_temp = this.category_sel;
            this.category_sel = ''
        },
        closeCate() {
            this.category_temp = ''
        },
        innerCancel() {
            this.innerVisible = false;
            this.form.category = "";
        },
        innerConfirm() {
            this.form.category = this.category_temp
            this.innerVisible = false;
        },
        innerImgCancel() {
            this.innerVisibleImg = false;
            this.form.image = "";
            this.isSubmit = true
        },
        innerImgConfirm() {
            this.innerVisibleImg = false;
        },
        CancelSub() {
            this.dialogFormVisible = false;
            this.ClearContent();
        },
        openDialog() {
            console.log("打开dialog");
            let data = JSON.parse(localStorage.getItem('goodsMessage'));
            console.log(data)
            if (data) {
                this.code = 1;
                this.form.id = data.id;
                this.isSubmit = true;
                this.form.category = data.category;
                this.form.name = data.name;
                this.form.price = data.price;
                this.form.num = data.number;
                this.form.image = data.photo;
                this.form.sellPoint = data.SellingPoint;
                this.form.desc = data.description;
                this.$nextTick(() => {
                    setTimeout(() => {
                        this.$refs.change.editor.txt.html(data.description);
                    }, 200)
                })
            } else {
                console.log("正常添加商品！")
            };
        },
        closeDialog() {
            this.ClearContent();
            localStorage.removeItem('goodsMessage')
        },
        ClearContent() {
            this.$refs.ruleForm.clearValidate();
            this.form.category = "";
            this.form.name = "";
            this.form.price = "";
            this.form.num = "";
            this.form.date = "";
            this.form.time = "";
            this.form.image = "";
            this.form.sellPoint = "";
            this.form.delivery = false;
            this.form.type = [];
            this.form.resource = "";
            this.form.desc = ""
            this.$refs.change.editor.txt.clear();
        },
        submitForm() {
            if (this.$refs.change.info_) {
                this.form.desc = this.$refs.change.info_;
            }
            this.$refs.ruleForm.validate((result) => {
                if (this.code == 0) {
                    if (result) {
                        this.dialogFormVisible = false;
                        this.$ajax({
                            method: "post",
                            url: "/api/goods_submit",
                            params: this.form
                        }).then(res => {
                            console.log(res)
                            this.$message({
                                message: '商品添加成功！',
                                type: 'success'
                            });
                            this.ClearContent()
                            this.reload()
                        });
                    } else {
                        this.$message({
                            message: '商品添加失败，请检查所填写内容！',
                            type: 'error'
                        });
                    }
                } else {
                    if (result) {
                        this.dialogFormVisible = false;
                        this.$ajax({
                            method: "post",
                            url: "/api/goods_editor",
                            params: this.form
                        }).then(res => {
                            this.code = 0;
                            console.log(res)
                            this.$message({
                                message: '修改商品成功！',
                                type: 'success'
                            });
                            this.ClearContent()
                            this.reload()
                        });
                    } else {
                        this.$message({
                            message: '修改商品失败，请检查所修改内容！',
                            type: 'error'
                        });
                    }
                }
            });
        },
        //上传图片
        submitUpload() {
            this.$refs.upload.submit();
        },
        handleRemove(file, fileList) {
            console.log(file, fileList);
        },
        handlePreview(file) {
            console.log(file);
        },
        onSuccess(response, file, fileList) {
            console.log('上传成功：');
            this.$message({
                message: '恭喜你，图片上传成功！',
                type: 'success'
            });
            // http://localhost:8989/1645580028699-1.png
            // upload\\1645580028699-1.png
            let imgUrl = response.url
            console.log(imgUrl);
            this.form.image = imgUrl;
            this.isSubmit = true
        },
        onError(err, file, fileList) {
        }
    },

    components: { WangEditor },
    inject: ['reload']
}
</script>

<style lang="less" scoped>
.line {
    text-align: center;
}
</style>